<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2015, http://www.gooraye.net. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Admin\Api;
use Admin\Model\MessageModel;
use Api\Vendor\UMeng\BoyePushApi;
use Common\Api\Api;
use Uclient\Api\UserApi;

class MessageApi extends Api{

    /**
     * 添加
     */
    const ADD = "Admin/Message/add";
    /**
     * 保存
     */
    const SAVE = "Admin/Message/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Admin/Message/saveByID";

    /**
     * 删除
     */
    const DELETE = "Admin/Message/delete";

    /**
     * 查询
     */
    const QUERY = "Admin/Message/query";
    /**
     * 查询一条数据
     */
    const GET_INFO = "Admin/Message/getInfo";

	/**
	 * 根据用户ID查询消息 前最新50条
	 */
	const QUERY_BY_UID = "Admin/Message/queryByUID";

	/**
	 * 查询所有消息分页
	 */
	const QUERY_MESSAGE = "Admin/Message/queryMessage";

	/**
	 * 记录消息
	 */
	const RECORD_MESSAGE = "Admin/Message/recordMessage";

	/**
	 * 推送消息
	 */
	const PUSH_MESSAGE = "Admin/Message/pushMessage";

	/**
	 * 根据消息ID推送消息
	 */
	const PUSH_MESSAGE_BY_MESSAGE_ID = "Admin/Message/pushMessageByMessageID";


	protected function _init(){
		$this->model = new MessageModel();
	}

	public function queryByUID($uid=0,$msg_type=0,$start_time=0){
		if(!is_numeric($uid)){
			$uid = 0;
		}
		if(!is_numeric($start_time)){
			$start_time=0;
		}

		$name = "";

		if($msg_type==1){
			$name = '系统消息';
		}
		if($msg_type==2){
			$name = '订单通知';
		}
		if($msg_type==3){
			$name = '物流通知';
		}
		if($name == ''){
			return $this->apiReturnErr("消息类型缺失");
		}

		$result = apiCall(UserApi::FIND,array(array('id'=>$uid)));
		if($result['status']){
			if(empty($result['info'])){
				return array('status'=>true,'info'=>'用户不存在！');
			}
		}else{
			return array('status'=>false,'info'=>$result['info']);
		}

		/*$query = "SELECT a.id,dtree_type,content,title,send_time,from_id,to_id,summary,status,msg_status FROM itboye_message as a,itboye_message_box as b where msg_id=a.id and to_id=$uid and send_time>$start_time order by send_time desc limit 0,50";
		$result = $this->model->query($query);*/

		$map = array(
			'to_id' => array('IN',array($uid,-2)),
			'send_time' => array('GT',$start_time),
			'msg_status' => array('NEQ',2),
			'status'=> 1,
			'name' => $name
		);
		$order = 'send_time desc';
		$field = 'name,msg_id,content,title,create_time,send_time,from_id,to_id,summary,msg_status,extra';
		$result = $this->model->alias("m")->join(" __MESSAGE_BOX__ as mb on m.id = mb.msg_id")
			->join("common_datatree as mc on m.dtree_type = mc.id",'left')
			->where($map)
			->order($order)
			->field($field)
			->limit(50)
			->select();

		if($result){
			return array('status'=>true,'info'=>$result);
		}else {
			if($result===false){
				return array('status'=>false,'info'=>$this->model->getDbError());
			}
			else{
				return array('status'=>true,'info'=>NULL);
			}
		}


	}

	public function queryMessage($map,$page = array('curpage'=>0,'size'=>10),$order = false, $params = false,$field=false){

		$list = $this->model->alias("m")->join(" __MESSAGE_BOX__ as  mb on m.id = mb.msg_id  ")
				->join("common_datatree as mc on m.dtree_type = mc.id",'left')
				->where($map)
				->order($order)
				->field($field)
				-> page($page['curpage'] . ',' . $page['size'])->select();

		$count = $this->model->alias("m")->join(" __MESSAGE_BOX__ as  mb on m.id = mb.msg_id  ")
			->join("common_datatree as mc on m.dtree_type = mc.id",'left')
			->where($map)
			->order($order)
			->field($field)
			-> count();

		if ($list === false) {
			$error = $this -> model -> getDbError();
			return $this -> apiReturnErr($error);
		}

		// 查询满足要求的总记录数
		$Page = new \Think\Page($count, $page['size']);

		//分页跳转的时候保证查询条件
		if ($params !== false) {
			foreach ($params as $key => $val) {
				$Page -> parameter[$key] = urlencode($val);
			}
		}

		// 实例化分页类 传入总记录数和每页显示的记录数
		$show = $Page -> show();

		return $this -> apiReturnSuc(array("show" => $show, "list" => $list));

	}

	public function getMessageByID($id){
		$map = array('m.id'=>$id);
		$list = $this->model->alias("m")->join(" __MESSAGE_BOX__ as  mb on m.id = mb.msg_id  ")
			->join("common_datatree as mc on m.dtree_type = mc.id",'left')
			->where($map)
			->field('m.id,dtree_type,title,content,from_id,summary,status,to_id')
			->find();

		if ($list === false) {
			$error = $this -> model -> getDbError();
			return $this -> apiReturnErr($error);
		} else {
			return $this -> apiReturnSuc($list);
		}

	}

	public function recordMessage($entity=array('title'=>'','to_id'=>0,'dtree_type'=>0,'from_id'=>0,'summary'=>'','send_time'=>0,'status'=>1,'extra'=>'')){
		if(empty($entity)){
			return $this -> apiReturnErr('entity参数缺失');
		}

		$message = array(
			'dtree_type'=>$entity['dtree_type'],
			'title'=>$entity['title'],
			'content'=>$entity['content'],
			'send_time'=>$entity['send_time'],
			'from_id'=>$entity['from_id'],
			'summary'=>$entity['summary'],
			'extra' => $entity['extra'],
			'status'=>$entity['status']
		);

		$result = $this->add($message);

		if(!$result['status']){
			return $this -> apiReturnErr($result['info']);
		}else{
			$id = $result['info'];
		}

		$message_box = array(
			'to_id' => $entity['to_id'],
			'msg_status'=>0,
			'msg_id'=>$id
		);

		$result = apiCall(MessageBoxApi::ADD,array($message_box));

		if(!$result['status']){
			return $this -> apiReturnErr($result['info']);
		}else{
			return $this -> apiReturnSuc('消息记录成功');
		}

	}

	/**
	 * 发送推送消息
	 */
	public function pushMessage($message=array('alert'=>0,'ticker'=>' ','title'=>' ','text'=>' '),$uid,$pushAll=false,$record=false){

		$param = array(
			'alert' => $message['alert'],
			'ticker' => $message['ticker'],
			'title' => $message['title'],
			'text' => $message['text' ]
		);

		vendor('BoyePushApi',APP_PATH.'Api/Vendor/Umeng/','.class.php');

		$BoyePushApi = new BoyePushApi();

		if($pushAll){
			$result = $BoyePushApi->sendAll($param);
		}else{
			$result = $BoyePushApi->send($uid,$param);
		}

		if($result['status']){

			if($record){
				//记录消息
				$result = apiCall(DatatreeApi::GET_INFO,array(array('name'=>L('MESSAGE_PUSH'))));
				if($result['status']){
					$dtree_type = !empty($result['info'])?$result['info']['id']:0;
				}else{
					$dtree_type = 0;
				}

				if($pushAll){
					$to_id = -2;
				}else{
					$to_id = $uid;
				}

				$entity = array(
					'title'=>$param['title'],
					'content'=>$param['text'],
					'to_id'=>$to_id,
					'dtree_type'=>$dtree_type,
					'from_id'=>0,//0:系统
					'summary'=>'',
					'send_time'=>time(),
					'status'=>1
				);
				$result = apiCall(MessageApi::RECORD_MESSAGE,array($entity));

				if($result['status']){
					return $this->apiReturnSuc('发送成功！');
				}else{
					return $this->apiReturnErr($result['info']);
				}
			}
			return $this->apiReturnSuc('发送成功！');

		}else{
			return $this->apiReturnErr($result['info']);
		}
	}

	/**
	 * 根据消息ID发送推送消息
	 */
	public function pushMessageByMessageID($id){

		//查找消息内容
		$result = $this->getMessageByID($id);
		if($result['status']){
			$message_info = $result['info'];
		}else{
			return $this->apiReturnErr($result['info']);
		}

		//推送消息
		$uid = $message_info['to_id'];
		$pushAll = false;
		if($uid==-2){
			$pushAll = true;
		}
		$message = array(
			'alert'=>$message_info['content'],
			'ticker'=>$message_info['title'],
			'title'=>$message_info['title'],
			'text'=>$message_info['content']
		);

		$result = $this->pushMessage($message,$uid,$pushAll);

		if($result['status']){
			return $this->apiReturnSuc('推送成功!');
		}else{
			return $this->apiReturnErr($result['info']);
		}

	}

	/**
	 * 记录并推送指定消息类型消息
	 */
	public function pushMessageAndRecordWithType($msg_type,$message=array('title'=>' ','content'=>' ','summary'=>' ','extra'=>''),$uid=0,$pushAll=false){

		//记录消息
		$result = apiCall(DatatreeApi::GET_INFO,array(array('name'=>$msg_type)));
		if($result['status']){
			$dtree_type = !empty($result['info'])?$result['info']['id']:0;
		}else{
			$dtree_type = 0;
		}

		if($pushAll){
			$to_id = -2;
		}else{
			$to_id = $uid;
		}

		$entity = array(
			'title'=>$message['title'],
			'content'=>$message['content'],
			'to_id'=>$to_id,
			'dtree_type'=>$dtree_type,
			'from_id'=>0,//0:系统
			'summary'=>$message['summary'],
			'extra'=>$message['extra'],
			'send_time'=>time(),
			'status'=>1
		);
		$result = apiCall(MessageApi::RECORD_MESSAGE,array($entity));

		if($result['status']){

			$msg = array(
				'alert'=>$message['content'],
				'ticker'=>$message['title'],
				'title'=>$message['title'],
				'text'=>$message['content']
			);

			$result = $this->pushMessage($msg,$uid,$pushAll);
			if($result['status']){
				return $this->apiReturnSuc('成功!');
			}else{
				return $this->apiReturnErr($result['info']);
			}


		}else{
			return $this->apiReturnErr($result['info']);
		}

	}

}
